package com.ptt.jituangou.widgets.listener

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * 手机号输入格式： 135 3783 9112
 */
class PhoneNumberTextWatcher constructor(private val editText: EditText) : TextWatcher {
    private var length = 0

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        length = mobileChanged(s, length)
    }

    override fun afterTextChanged(s: Editable?) {}


    private fun mobileChanged(s: CharSequence, length: Int): Int {
        val sb = StringBuilder()
        var index = s.length
        if (length < s.length) {
            //如果是输入字符
            when (s.length) {
                4 -> {
                    //1832
                    sb.append(s[0])
                    sb.append(s[1])
                    sb.append(s[2])
                    sb.append(" ")
                    sb.append(s[3])
                    index++
                    editText.setText(sb.toString())
                    editText.setSelection(index)
                }
                9 -> {
                    //183 21859
                    sb.append(s[0])
                    sb.append(s[1])
                    sb.append(s[2])
                    sb.append(s[3])
                    sb.append(s[4])
                    sb.append(s[5])
                    sb.append(s[6])
                    sb.append(s[7])
                    sb.append(" ")
                    sb.append(s[8])
                    index++
                    editText.setText(sb.toString())
                    editText.setSelection(index)
                }
            }
        } else {
            //如果是输入字符  删除字符
            when (s.length) {
                4 -> {
                    //183 2
                    sb.append(s[0])
                    sb.append(s[1])
                    sb.append(s[2])
                    index--
                    editText.setText(sb.toString())
                    editText.setSelection(index)
                }
                9 -> {
                    //183 2185 9
                    sb.append(s[0])
                    sb.append(s[1])
                    sb.append(s[2])
                    sb.append(s[3])
                    sb.append(s[4])
                    sb.append(s[5])
                    sb.append(s[6])
                    sb.append(s[7])
                    index--
                    editText.setText(sb.toString())
                    editText.setSelection(index)
                }
            }
        }
        return index
    }
}